const Router = require('koa-router')
const bcrypt = require('bcryptjs')
const {
  ThrowError,
  ExsitError,
  NotExsitError,
  PasswordError,
  ValidatorError
} = require('../../core/error')
const {requireParams} = require('../../core/my-validator')
const {User} = require('../modules/user')
const {getToken} = require('../../core/util')

const router = new Router({
  prefix: '/user'
})

// 示例
router.post('/test/:id/testapi', async ctx => {
  // 校验必传参数是否都存在, 用法请查看 requireParams 方法定义
  requireParams(ctx, [['id', 'params'], ['uname.firstName', 'body'], ['type', 'query'], ['token', 'header']])
  let params = ctx.params
  let query = ctx.request.query
  let header = ctx.request.header
  let body = ctx.request.body

  ctx.body = {
    code: 10000,
    data: {
      id: params.id,
      type: query.type,
      token: header.token,
      uname: body.uname,
      password: body.password
    }
  }
})

// 注册
router.post('/register', async ctx => {
  requireParams(ctx, [['uname', 'body'], ['password', 'body'], ['phone', 'body']])
  let body = ctx.request.body
  if(/^[a-zA-Z0-9]{6,16}$/.test(body.password)){
    let havePhone = await User.findOne({
      where: {
        phone: body.phone
      }
    })
    if(!havePhone){
      let result = await User.create(body)
      ctx.body = {
        code: 10000,
        data: {
          id: result.id,
          type: result.type,
          uname: body.uname,
          phone: result.phone
        }
      }
    }else{
      throw new ExsitError()
    }
  }else{
    throw new ValidatorError('请输入6-16位数字字母密码')
  }
})

// 登录
router.post('/login', async ctx => {
  requireParams(ctx, [['phone', 'body'], ['password', 'body']])
  let body = ctx.request.body
  let havePhone = await User.findOne({
    where: {
      phone: body.phone
    }
  })
  if(havePhone){
    if(bcrypt.compareSync(body.password, havePhone.password)){
      // 获取token
      let token = getToken(havePhone.id, havePhone.type)
      ctx.body = {
        code: 10000,
        data: {
          id: havePhone.id,
          type: havePhone.type,
          uname: havePhone.uname,
          phone: havePhone.phone,
          token
        }
      }
    }else{
      throw new PasswordError()
    }
  }else{
    throw new NotExsitError()
  }
})

module.exports = router